package com.wuming.house.controller;

import com.wuming.house.core.CommonResult;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.Houseprice;
import com.wuming.house.service.HousepriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author xuhuai
 * @createTime 2019/8/27 18:51
 * @Description:
 */
@Controller
@RequestMapping("/web/houseprice")
public class HousepriceController extends BaseController {

    @Autowired
    private HousepriceService housepriceService;

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult list(@RequestParam(required = false) String city) {
        logger.info("查询城市:{}的房价", city);
        try {
            List<Houseprice> houseprices = housepriceService.getHousepriceByCity(city, null, null);
            return CommonResult.createSuccessResult(houseprices, houseprices.size(), "查询城市房价成功");
        } catch (Exception e) {
            logger.error("查询城市房价异常,异常信息:{}", e.getMessage());
            return CommonResult.createFailureResult("查询城市房价失败");
        }
    }

    @RequestMapping("/toManageHouseprice")
    public String toManageHouseprice() {
        return "/tools/manageHouseprice";
    }

    @RequestMapping("/toAddHouseprice")
    public String toAddHouseprice() {
        return "/tools/editHouseprice";
    }

    @RequestMapping("/toEditHouseprice/{id}")
    public String toEditHouseprice(@PathVariable Long id, Model model) {
        Houseprice houseprice = housepriceService.getHousepriceById(id);
        model.addAttribute("houseprice", houseprice);
        return "/tools/editHouseprice";
    }

    @ResponseBody
    @RequestMapping(value = "/save")
    public CommonResult save(Houseprice houseprice) {
        List<Houseprice> houseprices = housepriceService.getHousepriceByCity(houseprice.getCity(), houseprice.getYear(), houseprice.getMonth());
        if (null == houseprices || houseprices.isEmpty()) {
            houseprice.setCreateDatetime(new Date());
            housepriceService.saveHouseprice(houseprice);
            return CommonResult.createSuccessResult(houseprice, 1, "保存城市房价成功");
        } else {
            housepriceService.modifyHouseprice(houseprice);
            return CommonResult.createSuccessResult(houseprice, 1, "保存城市房价成功");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}")
    public JsonResult delete(@PathVariable Long id){
        try {
            housepriceService.deleteById(id);
            return new JsonResult(null,"删除房价成功",true);
        }catch (Exception e){
            logger.error("删除房价失败,失败信息:{}",e.getMessage());
            return new JsonResult(null,"删除房价失败",false);
        }
    }

}
